import Vue from 'vue';
import Vuex from 'vuex';
import course from './modules/course';
import circle from './modules/circle';
import axios from 'axios';
import store from '@/store';
import {examAutoSubmitTime, appInd} from '../../config/loginConfig';
import { setToken, getToken } from '../utils/utils';
import Watermark from '@/libs/watermark.js';
Vue.use(Vuex);
export default new Vuex.Store({
    modules: {
        course,
        circle,
        config: {
            state: {
                dataDpr: 1,
                pkFontSize: 14,
                pkHtmlFontSize: 16,
                appUrl: window.localStorage.getItem('login-url'),
                appInd,
                userName: '',
                examAutoSubmitTime,
                loginUser: Object,
                plus: window.plus,
                isFirstLogin: false, //因业务相关改变，该字段与logincredit有关，logincredit>0为true
                loginCredit: '', //登入积分
                keepAliveList: [], //存放需要缓存的页面
                downloadCourseTaskList: [],
                downloadCourseModTask: new Map(),
                iosHeaderShow: true//ios系统中，header遮挡了其他层次，在样式上没有找到解决方法，故临时方案使用js处理
            },
            getters: {
                getUserName: (state, getters) => {
                    return state.userName;
                },
                getAppUrl: (state, getters) => {
                    return state.appUrl;
                },
                getDownloadCourseTask: (state, getters) => (courseId) => {
                    let downloadCourseTaskList = state.downloadCourseTaskList;
                    let targetObj = '';
                    for (let i = 0; i < downloadCourseTaskList.length; i++) {
                        targetObj = downloadCourseTaskList[i];
                        if (targetObj.courseId === courseId) {
                            break;
                        }
                        targetObj = '';
                    }
                    return targetObj;
                },
                getDownloadCourseModTask: (state, getters) => (key) => {
                    return state.downloadCourseModTask.get(key);
                },
                isExistKeepAliveList: (state) => (val) => {
                    return (state.keepAliveList.indexOf(val) !== -1);
                }
            },
            mutations: {
                setToken(state, token) {
                    state.token = token;
                    setToken(token);
                },
                setLoginUser(state, loginUser) {
                    state.loginUser = loginUser;
                },
                setUserName(state, loginUser) {
                    state.userName = loginUser;
                },
                setAppUrl(state, url) {
                    if (process.env.NODE_ENV === 'production_app') {
                        window.localStorage.setItem('login-url', url);
                        state.appUrl = url;
                        const baseURL = state.appUrl;
                        let axiosInstance = axios.create({
                            baseURL: baseURL // 设置baseurl
                        });
                        axiosInstance.interceptors.request.use(config => {
                            const token = window.localStorage.getItem('token');
                            if (token) {
                                config.withCredentials = true; // 允许携带token ,这个是解决跨域产生的相关问题
                                config.headers = {
                                    'developer': 'mobile',
                                    'token': token,
                                    'Content-Type': 'application/json;charset=UTF-8'
                                };
                            }
                            return config;
                        }, err => {
                            return Promise.reject(err);
                        });
                        Vue.prototype.$axios = axiosInstance;
                    } else {
                        state.appUrl = '';
                    }
                },
                setPlus(state, plus) {
                    state.plus = plus;
                },
                setIsFirstLogin(state, type) {
                    state.isFirstLogin = type;
                },
                setLoginCredit(state, num) {
                    state.loginCredit = num;
                },
                setIosHeaderShow(state, flag) {
                    state.iosHeaderShow = flag;
                },
                addKeepAliveList(state, name) {
                    let keepAliveList = state.keepAliveList;
                    if (keepAliveList.indexOf(name) === -1) {
                        keepAliveList.push(name);
                    }
                    state.keepAliveList = keepAliveList;
                },
                removeKeepAliveList(state, name) {
                    let keepAliveList = state.keepAliveList;
                    if (keepAliveList.indexOf(name) !== -1) {
                        keepAliveList.splice(keepAliveList.indexOf(name), 1);
                    }
                    state.keepAliveList = keepAliveList;
                },
                clearKeepAliveList(state) {
                    state.keepAliveList = [];
                },
                setDownloadTaskCourse(state, downloadCourseTask) {
                    state.downloadCourseTaskList = downloadCourseTask;
                },
                addDownloadTaskCourse(state, downloadCourseTask) {
                    let downloadCourseTaskList = state.downloadCourseTaskList;
                    //先删除在添加
                    let removeIndex = 0;
                    for (let i = 0; i < downloadCourseTaskList.length; i++) {
                        let temp = downloadCourseTaskList[i];
                        if (temp.courseId === downloadCourseTask.courseId) {
                            break;
                        }
                        removeIndex++;
                    }
                    state.downloadCourseTaskList.splice(removeIndex, 1);
                    state.downloadCourseTaskList.unshift(downloadCourseTask);
                },
                setDownloadCourseModTask(state, downloadCourseModTask) {
                    state.downloadCourseModTask = downloadCourseModTask;
                },
                putDownloadCourseModTask(state, obj) {
                    let downloadCourseModTask = state.downloadCourseModTask;
                    downloadCourseModTask.set(obj.key, obj.value);
                    state.downloadCourseModTask = null;
                    state.downloadCourseModTask = downloadCourseModTask;
                },
                removeDownloadCourseModTask(state, obj) {
                    //找到相对应的课程
                    let downloadCourseTaskList = state.downloadCourseTaskList;
                    let course;
                    let courseIndex;
                    for (let i = 0; i < downloadCourseTaskList.length; i++) {
                        course = downloadCourseTaskList[i];
                        if (parseInt(course.courseId) === parseInt(obj.courseId)) {
                            courseIndex = i;
                            break;
                        }
                    }
                    state.downloadCourseTaskList.splice(courseIndex, 1);
                    //找到相对应的模块
                    if (course.modules && course.modules.length > 0) {
                        let modIndex = -1;
                        for (let i = 0; i < course.modules.length; i++) {
                            if (parseInt(obj.modId) === parseInt(course.modules[i])) {
                                modIndex = i;
                                break;
                            }
                        }
                        course.modules.splice(modIndex, 1);
                        //添加任务
                        if (course.modules.length > 0) {
                            state.downloadCourseTaskList.unshift(course);
                        }
                        state.downloadCourseModTask.delete(obj.modId);
                    }
                }
            },
            actions: {
                // 登录
                handleTokenLogin({ commit }, params) {
                    return new Promise((resolve, reject) => {
                        Vue.prototype.$axios({
                            method: 'POST',
                            url: '/app/user/single/userlogin/auth',
                            params: params,
                            headers: {
                                common: {
                                    'developer': 'mobile'
                                }
                            }
                        }).then(res => {
                            if (res.data) {
                                const data = res.data.result;
                                commit('setToken', data.token);
                                resolve(res);
                            }
                        }).catch(err => {
                            reject(err.data);
                        });
                    });
                },
                handleWaterMark({ commit }, params) {
                    return new Promise((resolve, reject) => {
                        Vue.prototype.$axios({
                            method: 'GET',
                            url: '/app/api/system-setting/water-mark',
                            timeout: 1000,
                            headers: {
                                'Content-type': 'application/json'
                            }
                        }).then(res => {
                            let result = res;
                            let waterMark = result.data;
                            if (waterMark.value === 'ON') {
                                let userName = window.localStorage.getItem('usrSteUsrId') ? window.localStorage.getItem('usrSteUsrId') : '';
                                Watermark.set(userName);
                            }
                            window.localStorage.setItem('waterMarkSwitch', waterMark.value);
                            resolve(res);
                        }).catch(err => {
                            reject(err.data);
                        }); ;
                    });
                },
                getUserInfo({ store, commit }, params) {
                    return new Promise((resolve, reject) => {
                        Vue.prototype.$axios({
                            method: 'GET',
                            url: '/app/api/user/current',
                            timeout: 1000,
                            headers: {
                                'Content-type': 'application/json'
                            }
                        }).then(res => {
                            let result = res;
                            /*存储userInfo*/
                            window.localStorage.setItem('userInfo', JSON.stringify(res.data));
                            window.localStorage.setItem('usrSteUsrId', result.data.usrSteUsrId);
                            resolve(res);
                        }).catch(err => {
                            reject(err.data);
                        }); ;
                    });
                }
            }
        }
    }
});
